
accessid= 'LTAIjUf5VVzv5Kr9';
accesskey= 'jkDDtWtWVoylvsWA2XzXEmrU0kbuRn';
host = 'http://bankproject.oss-cn-shenzhen.aliyuncs.com';

g_dirname = ''
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000; 

var Img_num = 0;
var success_img = 0;
var ImgUpload = false;

var policyText = {
    "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
    ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
    ]
};

var policyBase64 = Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
var signature = Crypto.util.bytesToBase64(bytes);

function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ )
    {
        if(tt[i].checked)
        {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}

function get_dirname()
{
    dir = document.getElementById("dirname").value;
    if (dir != '' && dir.indexOf('/') != dir.length - 1)
    {
        dir = dir + '/'
    }
    //alert(dir)
    g_dirname = dir
}

function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{

    g_object_name += "${filename}"
    return ''
}

function get_uploaded_object_name(filename)
{

    tmp_name = g_object_name
    tmp_name = tmp_name.replace("${filename}", filename);
    return tmp_name

}

function set_upload_param(up, filename, ret)
{
    g_object_name = g_dirname;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });
    

    up.start();
}

function remove_upload_img(up, num){
	up.removeFile(up.files[num-1]);
	document.getElementById("fileAddr").value = "";
	for(var i=0;i<9;i++){
		document.getElementById("preImg_"+ (i+1)).height = "0px";
		document.getElementById("preImg_"+(i+1)).src = "";
		document.getElementById("prebtn_"+(i+1)).style.display = "none";
	}
	for(var i =0;i<up.files.length;i++){
		var value = document.getElementById("fileAddr").value;
		document.getElementById("preImg_"+(i+1)).src = up.files[i].imgsrc;
		document.getElementById("prebtn_"+(i+1)).style.display = "inherit";
		document.getElementById("fileAddr").value = value + "," + up.files[i].name;
	}
	Img_num--;
}


var uploader = new plupload.Uploader({
	runtimes : 'html5,flash,silverlight,html4',
	browse_button : 'selectfiles', 
    //multi_selection: false,
	container: document.getElementById('container'),
	flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
	silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',
    filters : [ {
                title : 'Image files',
                extensions : 'jpg,gif,png'
            }],

	init: {
		PostInit: function() {
			document.getElementById('postfiles').onclick = function() {
            set_upload_param(uploader, '', false);
            return false;
			};
		},

		FilesAdded: function(up, files) {
			plupload.each(files, function(file) {
				if(uploader.files.length > 9) { // 最多上传3张图
                    alert("只能上传一个文件，请删除多余文件！");
                    uploader.removeFile(files[1]);
                    return;
               }
				var preloader = new mOxie.Image();
				preloader.onload = function(){
					var imgsrc = preloader.type == 'image/jpeg'?preloader.getAsDataURL('image/jpge', 80):preloader.getAsDataURL();
					var localImag= document.getElementById("localImag");
					file.imgsrc = imgsrc;
					Img_num++;
					document.getElementById("preImg_"+ Img_num).height = "115px";
					document.getElementById("preImg_"+ Img_num).src = imgsrc;
					document.getElementById("prebtn_"+ Img_num).style.display = "inherit";
					document.getElementById("fileAddr").value += "," + file.name;
					preloader.destroy();
					preloader = null;
					
				};
				preloader.load(file.getSource());
			});
		},

		BeforeUpload: function(up, file) {
            check_object_radio();
            get_dirname();         
            set_upload_param(up, file.name, true);
        },
    	
    	UploadProgress: function(up, file) {
//		var d = document.getElementById(file.id);
//		d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
//      var prog = d.getElementsByTagName('div')[0];
//		var progBar = prog.getElementsByTagName('div')[0]
//		progBar.style.width= 2*file.percent+'px';
//		progBar.setAttribute('aria-valuenow', file.percent);
//		console.log(file.percent);
		},


		FileUploaded: function(up, file, info) {
            if (info.status == 200)
            {
                success_img++;
            }
            else
            {
                alert(info.response);
            }
            if(success_img == up.files.length){
            	console.log("success");
            	document.getElementById("submitBtn").click();
            }
		},

		Error: function(up, err) {
			console.log(err)
			}
	}
});

uploader.init();
